<template>

  <div class="main">
    <header-nav-bar></header-nav-bar>
    <div class="box">
      <van-button type="success" size="small" @click="switchClick">切换</van-button>
      <van-button type="success" size="small" style="float: right" @click="addFamily">添加家人</van-button>
      <div class="QRCode" @click="refresh">
        <van-image
            fit="contain"
            :src="imageSrc"
        />
      </div>
    </div>
    <div class="bottom">
      <div v-if="flag" class="owner">
        <van-row style="padding-top: 10px;">
          <van-col span="16"><span>{{ address }}</span></van-col>
          <van-col span="8"><span>{{ username }}</span></van-col>
          <van-col span="24" style="text-align: center">
            <span style="font-size: 30px;">{{ status }}</span>
          </van-col>
        </van-row>
      </div>
      <div v-if="!flag">
        <div class="addUser" @click="addUser">
          <van-icon name="plus" size="60" style="margin: auto;border: 3px solid black; border-radius: 40px;"/>
          <span style="font-size: 20px;">录入业主信息</span>
        </div>
      </div>

    </div>

    <bottom-tabbar :index="index"></bottom-tabbar>
    <!--    切换-->
    <van-dialog v-model:show="show" title="标题" show-cancel-button>
      <van-contact-list
          v-model="chosenContactId"
          :list="userList"
          default-tag-text="默认"
          add-text="切换"
          @add="onAdd"
          @select="onSelect"
      />
    </van-dialog>
  </div>


</template>

<script setup lang="ts">
import {Toast, Dialog, List} from 'vant';
import {nextTick, onMounted, reactive, ref, defineAsyncComponent, onBeforeUnmount} from "vue";

//异步加载组件
const headerNavBar = defineAsyncComponent(() =>
    import('@/components/HeaderNavBar.vue')
)
const bottomTabbar = defineAsyncComponent(() =>
    import('@/components/bottomTabbar.vue')
)

// import headerNavBar from "@/components/HeaderNavBar.vue"
// import bottomTabbar from "@/components/BottomTabbar.vue"
import {useRouter} from 'vue-router'
import {userStore} from '@/store/userStore.ts'
import {qrcode, getUserInfo, getUserStatus} from '@/service/nucleicAcid.js'


const VanDialog = Dialog.Component;

let router = useRouter()
const store = userStore()
const index = 0
const flag = ref(false)
//是否已登录
// const loginFlag = ref(false)
// const phone = ref('')
const userId = ref("")
const username = ref("")
const address = ref("")
const status = ref("今日未做")
const show = ref(false)

const loading = ref(false);
const finished = ref(false);

const chosenContactId = ref('1');
const userList = ref([]);
const choseContact = ref(null)


const imageSrc = ref("")

const timeInter = ref(null)

const onAdd = () => {
  if (choseContact.value == null) {
    show.value = false
    return
  }
  username.value = choseContact.value.name;
  address.value = choseContact.value.address;
  userId.value = choseContact.value.id
  show.value = false

  getQrcode()
  userStatus(userId.value)
};

const onSelect = (contact: any) => {
  choseContact.value = contact
}


onMounted(async () => {
  //接受路由参数
  //query
  // let userId=useRoute.query.userId;
  //params
  // let userId=useRoute.params.userId;

  //接收路由参数
  // loginFlag.value = router.currentRoute.value.query.loginFlag
  // phone.value = router.currentRoute.value.query.phone

  //获取二维码

  getQrcode()


  if (timeInter.value == null) {
    timeInter.value = setInterval(() => {
      getQrcode() // methods里的方法
    }, 60000)
  }

  showUser()
})

//页面销毁时触发
onBeforeUnmount(() => {
  clearInterval(timeInter.value);
})


const addUser = () => {
  if (!store.loginFlag) {
    const toast = Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '当前未登录，请先登录！',
    });

    let second = 3;
    const timer = setInterval(() => {
      second--;
      if (second) {
        toast.message = `倒计时 ${second} 秒`;
      } else {
        clearInterval(timer);
        Toast.clear();
        router.push("/login")
      }
    }, 1000);
  } else {
    router.push(
        {
          path: "/user",
          query: {phone: store.phone}
        })
  }

}

const addFamily = () => {
  if (!store.loginFlag) {
    const toast = Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '当前未登录，请先登录！',
    });

    let second = 3;
    const timer = setInterval(() => {
      second--;
      if (second) {
        toast.message = `倒计时 ${second} 秒`;
      } else {
        clearInterval(timer);
        Toast.clear();
        router.push("/login")
      }
    }, 1000);
  } else {
    router.push(
        {
          path: "/user",
          query: {id: store.userInfo.id}
        })
  }
}


const refresh = () => {
  getQrcode()
}

const switchClick = () => {
  show.value = !show.value
  loadContactList()
}


const getQrcode = async () => {
  let params = {
    "userId": userId.value
  }
  let res = await qrcode(params)
  if (res.data.code === 200) {
    imageSrc.value = "data:image/png;base64," + res.data.data
  }
}

const showUser = async () => {
  let userInfo = await loadUserInfo()
  flag.value = true
  username.value = userInfo.username
  address.value = userInfo.community + "," + userInfo.unit + " " + userInfo.floor_room_number
  store.username = userInfo.username;
  store.address = userInfo.community + "," + userInfo.unit + " " + userInfo.floor_room_number;
  store.userId = userInfo.id
  userId.value = userInfo.id
  userStatus(userInfo.id)
  // nextTick(() => {
  //   loadContactList()
  // })
}


const loadUserInfo = async () => {
  userList.value = []
  //先从store中获取
  // let userInfo = store.userInfo
  let userInfo;
  if (userInfo == undefined || userInfo.username == undefined) {
    let params = {
      "phone": store.phone
    }
    let ret = await getUserInfo(params)
    if (ret.data.code === 200) {
      store.userInfo = ret.data.data
      userInfo = ret.data.data
    }
  }
  return userInfo
}

const loadContactList = async () => {
  let userInfo = await loadUserInfo()
  let user = {
    "id": userInfo.id,
    "name": userInfo.username,
    "tel": userInfo.phone,
    "address": userInfo.community + "," + userInfo.unit + " " + userInfo.floor_room_number,
    "status": "",
    "isDefault": true,
  }
  userList.value.push(user)

  let familyList = userInfo.familyList
  familyList.forEach(function (value: any) {
    let user = {
      "id": value.id,
      "name": value.username,
      "address": value.community + "," + value.unit + " " + value.floor_room_number,
      "tel": value.phone,
      "status": ""
    }
    userList.value.push(user)
  })
}

const userStatus = async (id: string) => {
  let params = {
    "userId": id
  }
  let res = await getUserStatus(params)
  if (res.data.code == 200) {
    if (res.data.data.status) {
      status.value = "今日已做"
    }else {
      status.value = "今日未做"
    }

  }
}


</script>

<style scoped>


.main {
  display: flex;
  flex-direction: column;
}


.header {
  width: 100%;
  background: tan;
}

.box {
  position: relative;
  top: 70px;
  width: 100%;
  height: 350px;
  background-image: url("@/assets/images/bj.jpg");
  background-size: 100% 400px;
  background-repeat: no-repeat;
}

.bottom {
  margin: auto;
  position: relative;
  top: 70px;
  width: 100%;
  height: 150px;
  background: greenyellow;
}

.QRCode {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  background: #f9f9f9;
}

.addUser {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-40%, -80%);
  -webkit-transform: translate(-40%, -80%);
  border: 1px dashed black;
}

.replay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
}

.owner {
  font-size: 20px;
  text-align: center;
}

/deep/ .van-image__img {
  border: 9px solid yellow;
}


</style>